
package com.isoft.controller;

import com.isoft.pojo.dto.UserLoginDTO;
import com.isoft.pojo.entity.SystemUserLogin;
import com.isoft.result.Result;
import com.isoft.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@Tag(name = "用户接口")
@RequestMapping("/admin/user")
@RestController
@Slf4j
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    private HttpServletRequest request;

    /*
    用户登录控制器
    */
    @PostMapping("/login")
    @Operation(summary = "管理员登录接口")
    public Result login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("用户登录：{}", userLoginDTO);

        // 校验验证码（支持跳过验证）
        if (!validateCaptcha(userLoginDTO.getCaptcha())) {
            return Result.error("验证码错误或已过期");
        }

        SystemUserLogin loginInfo =  userService.login(userLoginDTO);
        if (loginInfo != null) {
            return Result.success(loginInfo);
        }
        else {
            return Result.error("用户名或密码错误");
        }
    }

    @GetMapping("/captcha")
    @Operation(summary = "生成图形验证码")
    public void captcha(HttpServletResponse response) throws IOException {
        // 生成验证码文本
        String captchaText = generateCaptchaText(4);

        // 生成验证码图片
        BufferedImage image = createCaptchaImage(captchaText);

        // 将验证码存入Session，设置5分钟过期
        HttpSession session = request.getSession();
        session.setAttribute("captcha", captchaText.toLowerCase());
        session.setMaxInactiveInterval(5 * 60);

        // 输出图片
        response.setContentType("image/png");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        ImageIO.write(image, "png", response.getOutputStream());
    }

    /*
     * 生成随机验证码文本
     */
    private String generateCaptchaText(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder captcha = new StringBuilder();
        for (int i = 0; i < length; i++) {
            captcha.append(chars.charAt(random.nextInt(chars.length())));
        }
        return captcha.toString();
    }

    /*
     * 创建验证码图片
     */
    private BufferedImage createCaptchaImage(String captchaText) {
        int width = 120;
        int height = 40;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();

        // 设置背景色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);

        // 添加干扰线
        Random random = new Random();
        g.setColor(Color.LIGHT_GRAY);
        for (int i = 0; i < 10; i++) {
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            g.drawLine(x1, y1, x2, y2);
        }

        // 绘制验证码
        g.setColor(Color.BLACK);
        g.setFont(new Font("Arial", Font.BOLD, 20));
        FontMetrics fm = g.getFontMetrics();
        int textWidth = fm.stringWidth(captchaText);
        int textHeight = fm.getAscent();
        int x = (width - textWidth) / 2;
        int y = (height + textHeight) / 2 - 5;
        g.drawString(captchaText, x, y);

        g.dispose();
        return image;
    }

    /*
     * 获取客户端IP地址
     */
    private String getClientIP() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            String ip = request.getHeader("X-Forwarded-For");
            if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
            return ip;
        }
        return "unknown";
    }

    /*
     * 验证验证码（支持可选验证）
     */
    private boolean validateCaptcha(String userInput) {
        // 如果用户未输入验证码，则视为不需要验证（Swagger测试用）
        if (userInput == null || userInput.trim().isEmpty()) {
            return true;
        }

        HttpSession session = request.getSession();
        String storedCaptcha = (String) session.getAttribute("captcha");

        if (storedCaptcha == null) {
            return false;
        }

        // 验证后删除验证码（一次性使用）
        session.removeAttribute("captcha");

        return storedCaptcha.equalsIgnoreCase(userInput.trim().toLowerCase());
    }
}